package com.changcheng.explorer;

import com.changcheng.explorer.event.IBOnClickListener;
import com.changcheng.explorer.event.GVOnItemClickListener;
import com.changcheng.explorer.event.MenuEvent;
import com.changcheng.explorer.service.FileListService;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.ImageButton;

public class FileList extends Activity {

	private static final String TAG = "FileList";
	private GridView gridView;
	private FileListService fileListService;
	private ImageButton ibSelect;
	
	public FileListService getFileListService() {
		return fileListService;
	}

	public void setFileListService(FileListService fileListService) {
		this.fileListService = fileListService;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);

		// gridView
		this.gridView = (GridView) this.findViewById(R.id.dir_gv_list);
		fileListService = new FileListService(this, gridView);
		this.gridView.setOnItemClickListener(new GVOnItemClickListener(
				this.fileListService));

		// ImageButton
		ImageButton ibHome = (ImageButton) this.findViewById(R.id.dirl_ib_home);
		ImageButton ibUp = (ImageButton) this.findViewById(R.id.dirl_ib_up);
		ImageButton ibBack = (ImageButton) this.findViewById(R.id.dirl_ib_back);
		ImageButton ibForward = (ImageButton) this
				.findViewById(R.id.dirl_ib_forward);
		ImageButton ibView = (ImageButton) this.findViewById(R.id.dirl_ib_view);
		ImageButton ibOperations = (ImageButton) this
				.findViewById(R.id.dirl_ib_operations);
		ibSelect = (ImageButton) this
				.findViewById(R.id.dirl_ib_select);

		// ImageButtonEvents
		ibHome.setOnClickListener(new IBOnClickListener(this));
		ibUp.setOnClickListener(new IBOnClickListener(this));
		ibBack.setOnClickListener(new IBOnClickListener(this));
		ibForward.setOnClickListener(new IBOnClickListener(this));
		ibView.setOnClickListener(new IBOnClickListener(this));
		ibOperations.setOnClickListener(new IBOnClickListener(this));
		ibSelect.setOnClickListener(new IBOnClickListener(this));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// 显示菜单
		getMenuInflater().inflate(R.menu.options_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// 菜单事件
		try {
			return MenuEvent.execute(this.fileListService, item);
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 设置按钮的选择状态
	 * @param state
	 */
	public void setSelectState(boolean state){
		if(ibSelect != null){
			if(state)
				ibSelect.setImageResource(R.drawable.select);
			else
				ibSelect.setImageResource(R.drawable.unselect);
		}
		if(fileListService != null)
			fileListService.setCanSelect(state);
	}
	
}